<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>放大镜</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .photo {
        position: relative;
        float: left;
        width: 300px;
        height: 400px;
        text-align: center;
        border: 1px solid #e3e3e3;
        overflow: hidden;
        cursor: move;
      }
      .photo img {
        margin-top: 20px;
      }
      .mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 150px;
        height: 150px;
        background-color: yellow;
        opacity: 0.3;
      }
      .show {
        float: left;
        width: 600px;
        height: 700px;
        border: 1px solid #e3e3e3;
        background: url("img/cet6.jpg") no-repeat;
        background-size: cover;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="photo">
        <img src="img/cet6.jpg" alt="shop" />
        <div class="mask"></div>
      </div>
      <div class="show"></div>
    </div>
    <script>
      var box = document.querySelector(".photo");
      var mask = document.querySelector(".mask");
      var show = document.querySelector(".show");
      box.addEventListener("mousemove", function (e) {
        var l = e.clientX - this.offsetLeft - mask.offsetWidth / 2,
          r = e.clientY - this.offsetTop - mask.offsetWidth / 2;
        if (l >= 0 && l <= this.offsetWidth - mask.offsetWidth)
          mask.style.left = l + "px";
        if (r >= 0 && r <= this.offsetHeight - mask.offsetHeight)
          mask.style.top = r + "px";
        // 遮罩层移动距离/遮罩层最大移动距离=大图片移动距离/大图片最大移动距离
        // show.style.backgroundPosition =
        //   -1 * l + "px " + -1 * (r + mask.offsetWidth - 100) + "px";
        var l1 =
            (l * show.offsetWidth) / 2 / (box.offsetWidth - mask.offsetWidth),
          r1 =
            (r * show.offsetHeight) /
            2 /
            (box.offsetHeight - mask.offsetHeight);
        show.style.backgroundPosition = -l1 + "px " + -r1 + "px";
      });
    </script>
  </body>
</html>
